package commons.base.util;

import java.lang.invoke.MethodHandle;
import java.lang.invoke.MethodHandles;
import java.lang.reflect.Field;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;

public class BeanUtil {

	private static MethodHandles.Lookup lookup = MethodHandles.lookup();
	
	public static <T> T fill(Class<T> clazz, Map<String, ? extends Object> map)throws Throwable{
		T bean = clazz.newInstance();
		
		Field[] fields = clazz.getDeclaredFields();
		if(fields != null){
			for(Field f : fields){
				if(map.containsKey(f.getName())){
					f.setAccessible(true);
					MethodHandle mh = lookup.unreflectSetter(f);
					
					Object value = map.get(f.getName());
					if((value != null) && (value instanceof String) && (!String.class.isAssignableFrom(value.getClass()))){
						// 类型不匹配，自动转换
						if(Integer.class.isAssignableFrom(value.getClass()) || Integer.TYPE.isAssignableFrom(value.getClass())){
							value = Integer.parseInt((String)value);
						}else if(Long.class.isAssignableFrom(value.getClass()) || Long.TYPE.isAssignableFrom(value.getClass())){
							value = Long.parseLong((String)value);
						}else if(Double.class.isAssignableFrom(value.getClass()) || Double.TYPE.isAssignableFrom(value.getClass())){
							value = Long.parseLong((String)value);
						}else if(Float.class.isAssignableFrom(value.getClass()) || Float.TYPE.isAssignableFrom(value.getClass())){
							value = Long.parseLong((String)value);
						}else if(Date.class.isAssignableFrom(value.getClass())){
							value = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse((String)value);
						}
					}
					
					mh.invoke(bean, value);
				}
			}
		}
		
		return bean;
	}
	
}
